#include "apue.h"
#include <sys/wait.h>
#include <errno.h>

#define DEF_PAGER   "/bin/more"

int main(int argc, char *argv[]) {
    int n;
    int fd[2];
    pid_t pid;
    char *paper, *argv0;
    char line[MAXLINE];
    FILE *fp;

    if (argc != 2)
        err_quit("usage: a.out <pathname>");
    if ((fp= fopen(argv[1], "r")) == NULL)
        err_sys("can't open %s", argv[1]);
    if (pipe(fd) < 0)
        err_sys("pipe error");

    if ((pid= fork()) < 0)
        err_sys("fork error");
    else if (pid > 0) { /* parent */ 
        close(fd[0]);
        while (fgets(line, MAXLINE, fp) != NULL) {
            n= strlen(line);
            if (write(fd[1], line, n) != n)
                err_sys("write error to pipe");
        }
        if (ferror(fp)) 
            err_sys("fgets error");

        close(fd[1]);   /* close write end of pipe of reader */
        if (waitpid(pid, NULL, 0) < 0) {
            if (errno != EINTR)
                err_sys("waitpid error");
        }
        exit(0);

    } else {    /* child */
        close(fd[1]);
        if (fd[0] != 0) {
            if (dup2(fd[0], 0) != 0)
                err_sys("dup2 error");
        }
        close(fd[0]);
        if ((paper= getenv("paper")) == NULL)
            paper= DEF_PAGER;
        if ((argv0= strrchr(paper, '/')) != NULL)
            argv0++;

        execl(paper, argv0, (char *)0);
        exit(1);
    }

}
